<?php

$path = dirname(__FILE__);
require($path.'/lib/crt.php');
require_once($path.'/lib/block.php');

//try {

$crt = new CRT();
$crt->init();

// Populate colors table if necessary
CRTBlock::checkColors();

if(isset($_REQUEST['loginSubmit'])) {
    $loginErr = true;

    $username = Clean::string($_REQUEST['username'], false, false, true);
    $password = Clean::string($_REQUEST['password'], false, false, true);

    if($username && $password) {
        $user = CRTUser::logIn($username, $password);
        if($user) {
            $loginErr = false;
            //                       header('Location: /');
            //                     exit;
        }
    }
}

// Authorize user
if(!$user)
    $user = $crt->getUser();

$op = Clean::string($_REQUEST['op'],false, false, true);

if(isset($_REQUEST['clearLoaded'])) {
    $op = null;
    CRTSession::set('loadedBlocks', null);
}

$ajax = $_REQUEST['ajax'] ? true : false;
if(!$ajax)
    CRTSession::set('loadedBlocks', null);

// Operate
switch($op) {

    case 'addBlock' :
        $id = Clean::int($_REQUEST['id']);
        $block = new CRTBlock($id);

        $nhs = CRTBlock::getNeighborhoods();
        $loaded = CRTSession::get('loadedBlocks');
        if($loaded) {
            array_push($loaded, $id);
        } else {
            $loaded = array($id);
        }

        CRTSession::set('loadedBlocks', $loaded);

        break;

    case 'removeBlock' :
        $id = Clean::int($_REQUEST['id']);
        $loaded = CRTSession::get('loadedBlocks');
        if(count($loaded)) {
            $key = array_search($id, $loaded);
            if($key!==false) {
                unset($loaded[$key]);
                CRTSession::set('loadedBlocks', $loaded);
            }
        }
        break;

    case 'setBlocks' :
        $source = Clean::string($_REQUEST['nhSource']);
        $blocks = is_array($_REQUEST['loadedBlocks']) ? Clean::intArray($_REQUEST['loadedBlocks'], false, true) : Clean::int($_REQUEST['loadedBlocks'], false, true);
        $nh = $source=='input' ? Clean::string($_REQUEST['addNh'], false, false, true) :Clean::string($_REQUEST['nhSelect'], false, false, true);

        // Add a new color for a new nh
        if($source=='input') {
            CRTBlock::addNhColor($nh);
        }

        if($nh && $blocks) {
            // Update the bloks
            if(!is_array($blocks))
                $blocks = array($blocks);

            if($user->role == EDITOR_ROLE) {
                // Assign nh to blocks
                CRTBlock::updateBlocks($blocks, $nh);
            } elseif($user->role==INFLUENCER_ROLE) {
                CRTBlock::addPending($blocks, $nh);
            }

            // Clear loaded
            CRTSession::set('loadedBlocks', null);

        }

        break;

    default:
        break;
}

$minX  = Clean::float($_REQUEST['minX'], false, true);
$maxX  = Clean::float($_REQUEST['maxX'], false, true);
$minY  = Clean::float($_REQUEST['minY'], false, true);
$maxY  = Clean::float($_REQUEST['maxY'], false, true);
$initZoom = Clean::int($_REQUEST['zoom'], false, true);
$initCenter = Clean::string($_REQUEST['center'], false, false, true);
$initCenter = preg_replace('/[\(\)"\s]/', '', $initCenter);

if(!$initCenter)
    $initCenter = INIT_CENTER;

if($minX && $maxX && $minY && $maxY)
    $extents = array('minX' => $minX, 'maxX' => $maxX, 'minY' => $minY, 'maxY' => $maxY);

$nhs = CRTBlock::getNeighborhoods($extents);
$loaded = CRTSession::get('loadedBlocks');

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

    <head>
        <title>HQ CRT</title>
        <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
        <?php
        $dir = opendir(PLUGIN_PATH.'/css');
        while(($file= readdir($dir))!==false) {
            echo '<link rel="stylesheet" href="/css/'.$file.'" type="text/css" media="all">';
        }

        ?>
    </head>

    <body>
        <div id='contentWrapper' style="width: 311px; float: left; "> <?php // Closed in footer.tpl.php ?>
            <!-- BEGIN_CONTENT_WRAPPER -->
            <?php if($user && $user->loggedIn()) : ?>
            <div id="userCtrls">
                <span>
                    <a class='ajaxBypass' href="/user/logout.php">Log out</a>
                </span>
                &nbsp;(<?php echo ($user->role==EDITOR_ROLE) ? 'Editor' : 'Influencer';?>)
                    <?php if($user->role==EDITOR_ROLE) : ?>
                <span><a href='/user/accounts.php'>Manage accounts</a></span>
                <br /><br />
                <span><a id='applyEditsLink' href='javascript: void(0);'>Apply all edits</a></span>
                <span><a id='rejectEditsLink' href='javascript: void(0);'>Reject all edits</a></span>

                <span><a class='helpLink' href='javascript:void(0);'>Help</a></span>

                    <?php endif; ?>

            </div>
            <?php else: ?>
            <div id='loginWrap'>
                <span><a id='loginLink' href='#'>Log in</a></span>
                <span><a class='helpLink' href='javascript:void(0);'>Help</a></span>


                <form id='loginForm' method='post' action='/' style="display: none;">
                    <h3>Login</h3>
                    <table>
                            <?php if($loginErr):?><tr><td colspan=2><span style='color:red; font-weight: bold;'>Invalid user/pass combination</span></tr></td><?php endif; ?>
                        <tr><td><label>Username:</label></td><td><input type='text' name='username' value='' /></td></tr>
                        <tr><td><label>Password:</label></td><td><input type='password' name='password' value='' /></tr>
                        <tr><td colspan=2>&nbsp;</td></tr>
                        <tr><td colspan=2><input type='submit' name='loginSubmit' value='Submit' /></td></tr>
                    </table>
                </form>
            </div>


            <?php endif; ?>

            <div id='helpWrap' style="display: none; border: 1px dotted gray; padding: 3px;">
                This map will work best in the Firefox and Chrome web browsers.
                <br /><br />
                1. You must log in to edit the map (<a href='mailto:<?php echo ROOT_EMAIL;?>'>email editor</a> to request an account) <br />
                2. Zoom in as far as possible to increase performance<br />
                3. Right click on any block in the map for additional info<br />
                4. Blocks displayed in red <div style='width: 5px; height: 2px; overflow: hidden; padding: 0; background-color: red; display: inline;'>&nbsp;&nbsp;&nbsp;</div> have pending edits<br />
                <?php if($user->role==EDITOR_ROLE): ?>
                5. To process changes, right click on a Pending RED block to apply or reject a single edit
                6. Click 'Apply all edits' or 'Reject all edits' for batch edits
                <?php endif; ?>
                <br /><br />


                <a class='helpLink' href='javascript:void(0);'>Help</a>

            </div>

            <?php if(true ) : ?>
            <br />
            <form action='/' method='POST'>
                <table id='blockModTbl' <?php if(!$user->loggedIn()) echo "style='display:none;'"; ?>>
                    <tr><td colspan=2><h3>Zoom in to edit neighborhoods</h3></td></tr>
                    <tr>
                        <td colspan=2><h3>1. Select blocks from the map</h3></td>
                    </tr>
                    <tr>
                        <td width=1 style='vertical-align: top;'><label>Selected&nbsp;Blocks:</label></td><td>&nbsp;&nbsp;<a href='javascript: void(0);' id='clearSelectedLink'>Clear</a></td>
                    </tr>
                    <tr>       <td colspan=2>
                            <select  multiple id="loadedBlocks" name='loadedBlocks[]'>
                                    <?php
                                    if(is_array($loaded) && count($loaded)) {
                                        foreach($loaded as $oid) {
                                            $b = new CRTBlock($oid);
                                            $name = ($b->NAME) ?  $b->NAME : 'No Name';

                                            echo "<option value='$oid' selected>$name - $oid</option>";
                                        }
                                    }
                                    ?>
                            </select>
                        </td>
                        <tr><td colspan=2><label>Display blocks:</label><input type='checkbox' name='displayLayers' id='displayLayers' value=1 checked /></td></tr>

                        <tr><td colspan=2>&nbsp;</td></tr>

                    </tr>

                    <tr><td colspan=2><h3>2. Assign blocks to a neighborhood</h3></td></tr>
                    <tr>
                        <td colspan=2><input type='radio' name='nhSource' value='select' checked /><label>Select Neighborhood:</label></td>
                    </tr>
                    <tr>
                        <td colspan=2>
                            <select name='nhSelect'id='nhSelect' style="width: 100%;">
                                    <?php foreach($nhs as $nh) : ?>
                                <option value='<?php echo $nh; ?>'><?php echo $nh; ?></option>
                                    <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>
                    <tr><td colspan=2>&nbsp;</td></tr>

                    <tr><td colspan=2><input type='radio' name='nhSource' value='input' /><label>Or add a neighborhood:</label></td></tr>
                    <tr><td colspan=2><input type='text' name='addNh' value='' /></td></tr>
                    <tr><td colspan=2>&nbsp;</td></tr>
                    <tr><td colspan=2>  <div style='color: #000000; overflow: hidden; height: 15px;' ><div id='pendingColor' style='float: left; background-color: #FFFFFF; width: 10px; height: 10px; '></div>&nbsp;-&nbsp;Block with pending changes</div>
                            </div>
                        </td></tr>

                    <tr><td colspan=2>&nbsp;</td></tr>


                    <tr><td colspan=2>
                            <input type='submit' name='nhSubmit' id='nhSubmit' value='Submit' <?php if(!$user->loggedIn()) echo 'disabled'; ?> />
                            <input type='submit' name='clearLoaded' id='clearLoaded' value='Clear' <?php if(!$user->loggedIn()) echo 'disabled'; ?> />
                            <input type='hidden' name='op' value='setBlocks' />
                            <input type='hidden' name='zoom' id='zoom' value='<?php echo $initZoom; ?>' />
                            <input type='hidden' name='center' id='center' value='<?php echo $initCenter; ?>' />
                            <input type='hidden' id='userRole' value="<?php echo $user->role; ?>" />
                        </td></tr>

                </table>
            </form>
            <br /><br />
            <div id='exportBox'>
                <h3>Export</h3>
                <!--                         <a class='evtBound' href='#' id='exportBtn'>Export</a> -->
                <form id='exportForm' method='POST' action='/ajax/export.php'>
                    <div id='exportSpinner' style='display: none;'>
                        <img style='width: 20px; height: 20px;' src='http://mportlandrealestate.com/wp-content/plugins/hq_idx/images/loading-spinner.gif' />
                        <span style='vertical-align: top; font-weight: bold;'>Loading...</span>
                    </div>

                    <div>
                        <label>Export Format:</label>
                        <input type='radio' name='exportFmt' value='shapefile' checked /> Shapefile
                        <input type='radio' name='exportFmt' value='kml' id='kmlExport' /> KML
                        <br />
                        <label>Export as:</label>
                        <input type='radio' name='exportObj' id='neighborhoodsExport' value='neighborhoods' checked /> Neighborhoods
                        <input type='radio' name='exportObj' id='blocksExport' value='blocks' /> Blocks
                        <br /><br />
                        <label>Selected:</label><span style='font-size: 10px;'>(Right click on a block)</span><br />
                        <select multiple id='exportNhs'></select>
                    </div>

                    <input type='submit' name='exportSubmit' value='Export Selected' class='exportBtn' /> <strong>or</strong> <br /><br />
                    <input type='submit' name='exportMetro' value='Export entire <?php echo METRO_NAME;?> metro' class='exportBtn' />
                    <br /><br />
                    <div id="exportMsg" style='display: none;'><a id='expDownloadLink' href="/ajax/shape.zip">Download</a></div>

                </form>
            </div>
            <br /><br />
                <?php if(defined('ROOT_EMAIL')) : ?>
            <span><a href='mailto:<?php echo ROOT_EMAIL; ?>'>Request an account to submit neighborhood edits</a></span>
                <?php endif; ?>
            <!--
            <div id='recreateNhBox'>
                     <a class='evtBound' href='#' id='recreateNHBtn'>Recreate neighborhood labels</a>
                    <br /><br />
                    <div id='nhSpinner' style='display: none;'>
                            <img style='width: 20px; height: 20px;' src='http://mportlandrealestate.com/wp-content/plugins/hq_idx/images/loading-spinner.gif' /><span style='vertical-align: top; font-weight: bold;'>Loading...</span>
                    </div>
                    <div style="display: none;" id='recreateNhMsg'>
                            Labels successfully recreated
                    </div>
            </div>
            -->

            <?php endif; ?>

            <!-- END_CONTENT_WRAPPER -->
        </div>
        <div>

            <div id='mapWrapper' style="float: left; width: 700px; height: 570px; overflow: hidden">
                <div id='mapShadowH'></div>
                <div id='mapShadowV'></div>
                <div id='map'  class="z12" style="position: relative; background-color: rgb(229, 227, 223);"></div>
                <div id="loadingMsg"><img height="32" width="32" src="/img/loading-spinner.gif"/></div>
                <div id="zoomReminder">
                    Zoom in to edit census blocks&nbsp;<a href='#' class='disabled' id='closeReminder'></a>
                </div>
                <div id="listingBalloon" style="display: none;"></div>

            </div>
            <div class='clear'></div>

            <div id="footer">
                <script type='text/javascript' src='http://maps.google.com/maps?file=api&v=2.s&key=<?php echo HQ_GOOGLE_MAPS_KEY; ?>'></script>\r\n
                <script type="text/javascript" src="/js/jquery/jquery-1.3.2.min.js"></script>
                <script type='text/javascript' src='/js/jquery/dimensions-1.2.js'></script>
                <script type='text/javascript'>var test = 'var';
                $j = jQuery.noConflict();</script>

                <?php if(USE_JS_COMPRESSION) : ?>
                <script type="text/javascript" src="/js/combined.js"></script>
                <?php else : ?>
                <script type="text/javascript" src="/js/toolbox.js"></script>
                <script type="text/javascript" src="/js/console.js"></script>
                <script type="text/javascript" src="/js/layout.js"></script>
                <script type="text/javascript" src="/js/map.js"></script>
                <script type='text/javascript' src='/js/elabel.js'></script>
                <script type='text/javascript' src='/js/labels.js'></script>
                <script type='text/javascript' src="/js/loadingMsg.js"></script>
                <script type="text/javascript" src="/js/space-polygon.js"></script>
                <script type="text/javascript" src="/js/zoom-reminder.js"></script>
                <script type="text/javascript" src="/js/export.js"></script>
                <?php endif; ?>

            </div>

            <script type='text/javascript'>
                var trans = null;

                $j(document).ready(function() {

                    GEvent.addListener( hq.map.gMap, 'moveend', getNeighborhoods);

                    function getNeighborhoods() {
                        var bounds = hq.map.getBounds();
                        if(trans) {
                            console.info('Aborting the last nh req');
                            trans.abort();
                            trans = null;
                        }

                        $j('#nhSelect').attr('disabled', true);

                        trans = $j.ajax({
                            dataType: 'json',
                            url : "/ajax/get-neighborhoods.php",
                            data: {
                                minX: bounds.minX,
                                maxX: bounds.maxX,
                                minY: bounds.minY,
                                maxY: bounds.maxY
                            },
                            success: function(res) {
                                var html = [];

                                for(var i=0; i<res.length; i++) {
                                    html[html.length] = "<option value='" + res[i] + "'>" + res[i] + "</option>";
                                }

                                $j('#nhSelect').html(html.join(',')).attr('disabled', '');
                            }
                        });
                }

                // Populate the select neighborhodds drop down
                getNeighborhoods();

                $j('#loginLink').toggle(function(evt) {
                    $j('#loginForm').show();
                    $j('#loginLink').html('Hide');
                },

                function(evt) {
                    $j('#loginForm').hide();
                    $j('#loginLink').html('Log in');
                }
            );


                $j('.helpLink').click(function(evt) {
                    $tgt = $j(evt.target);

                    if($j('#helpWrap:hidden').length > 0) {
                        $j('#helpWrap').show();
                        $j('.helpLink').html('Hide');
                    }
                    else {
                        $j('#helpWrap').hide();
                        $j('.helpLink').html('Help');
                    }

                }

            );


                // Export controls
                $j("input[name='exportFmt']").change(function(evt) {
                    var $tgt = $j(evt.target);
                    var id = $tgt.attr('id');


                    if($j('#kmlExport').is(':checked')) {
                        $j('#neighborhoodsExport').attr('checked', true);
                        $j('#blocksExport').attr('disabled', true);
                    } else {
                        $j('#blocksExport').attr('disabled', '');
                    }
                });
            });
            </script>

    </body>
</html>
